<?php

namespace App\Jobs;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use OpenAI;
use Rainsens\Dinglog\Facades\Dinglog;
use Illuminate\Support\Facades\Storage;

class TranslateVideoJob implements ShouldQueue
{
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
	
	public $model;

	public $timeout = 400;

	public function __construct($model)
	{
		$this->model = $model;
	}
	
	 public function handle()
    {

    	$model = $this->model;

    	$appKey = "2516e5d2ac024635b94d4161f5f85d27";
		$appSecret="50b79f090507412198bfeba9f0596a0b";
		
		$url = "https://api.zhaoli.com/v-w-c/gateway/ve/work/free";
		/*$url="https://api.zhaoli.com/v-w-c/gateway/ve/work/status";
		$data=[
			'idProjects'=>[229961010],
		];*/

		$videoUrl= "";
		if(strstr($model->video_url,"http")){

			$videoUrl = $model->video_url;
		}else{

			$videoUrl = "https://xbreaking.oss-cn-beijing.aliyuncs.com".$model->video_url;
		}


		$data = array(
		    "urls" => [$videoUrl],
		    "voice" => 1,
		    "wyVoiceParam" => "{\"id\":62,\"font_param\": {\"style\": \"tpl-31-1-T\",\"font_size\": 32,\"position\": 0.727}}",
		    "lang" => "en",
		    "sourceLang" => "zh",
		    "removeBgAudio" => 1,
		    "needChineseOcclude" => 11,
		    "needTrim" => 0,
		    "needMask" => 0,
		    "needMirror" => 0,
		    "needRescale" => 0,
		    "resolution" => 1,
		    "wyNeedText"=>1,
		    "needWanyin"=>1,
		    "wyTaskType"=>"FULL",
		    "callback" => "https://api.xbreakingtechinsight.com/ghostcut/return",
		    "workName" => "Video".$model->id,
		);
		$body = json_encode($data);
		$md5_1 = md5($body, true);
		$md5_2 = md5(bin2hex($md5_1) . $appSecret, true);
		$sign = bin2hex($md5_2);
	    
	    $header = array(
		    'Content-type: application/json',
		    'AppKey: ' . $appKey,
		    'AppSign: ' . $sign,
		);

		$res = $this->curl($url,$body,$header);
		
		$result = json_decode($res,true);
		
		if($result['msg']=="success"){

			$model->update(['ghost_project_id'=>$result['body']['idProject']]);
		}


		//486368421
		//229954001
    }


    

    public function curl($url,$body,$header){

    	
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

		$response = curl_exec($ch);
		curl_close($ch);

	   //dd($response);
	   return $response;
	}
}
